package com.f21.f21assessoria.config;

import java.util.Collection;

import javax.sql.DataSource;

import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.cloudfoundry.runtime.env.RdbmsServiceInfo;
import org.cloudfoundry.runtime.service.relational.RdbmsServiceCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {

	@Autowired
	@Qualifier("dslocal")
	DataSource dsLocal;

	private CloudEnvironment cloudEnvironment = new CloudEnvironment();
	
	@Bean(name ="dDataSource")
	public DataSource getDataSource() {
		
		if (cloudEnvironment.isCloudFoundry())
			return getCFDataSource();
		else
			return dsLocal;
	}
	
	private DataSource getCFDataSource() {
		System.out.println("entou no CF");
		Collection<RdbmsServiceInfo> sqlServiceInfo = cloudEnvironment.getServiceInfos(RdbmsServiceInfo.class);
		RdbmsServiceCreator dataSourceCreator = new RdbmsServiceCreator();
		return dataSourceCreator.createService(sqlServiceInfo.iterator().next());
	}

}
